package com.lsp.servelt;

import com.alibaba.fastjson.JSON;
import com.lsp.bean.Handler;
import com.lsp.bean.Model;
import com.lsp.helper.*;
import com.lsp.util.ReflectionUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        //初始化相关的helper类
        LoaderHelper.init();

        // 获取servletContext对象，用于注册Servlet
        ServletContext servletContext = config.getServletContext();
    }



    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestMethod = req.getMethod().toUpperCase();
        String requestPath = req.getRequestURI();

        String[] splits = requestPath.split("/");
        if(splits.length > 2){
            requestPath = "/" + splits[2];
        }

        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        if(handler != null){
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = BeanHelper.getBean(controllerClass);

            //调用与请求对应的方法(这里类似于SpringMvc的处理器适配器)
            Object result;
            Method controllerMethod = handler.getControllerMethod();

            //初始化参数(自动注入，并返回)
            Object param = RequestHelper.creteParam(req,controllerMethod);

            if(param == null){
                result = ReflectionUtil.invokeMethod(controllerBean,controllerMethod);
            }else{
                result = ReflectionUtil.invokeMethod(controllerBean,controllerMethod, param);
            }

            //返回JSON数据
            if(result instanceof Model){
                handlerDataResult((Model) result,resp);
            }
        }
    }

    /**
     * 返回Json数据
     */
    private void handlerDataResult(Model data,HttpServletResponse response) throws IOException {
        Object model = data.getModel();
        if(model!= null){
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter responseWriter = response.getWriter();
            String json = JSON.toJSON(model).toString();
            responseWriter.write(json);
            responseWriter.flush();
            responseWriter.close();
        }
    }


}
